package com.baseframe.create1.util;

import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;


import com.baseframe.create1.MainActivity;
import com.baseframe.create1.R;
import com.baseframe.create1.dialog.LoadingDialog;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;


/**
 * 更新 manager
 */
public class UpdateManager {
    /* 下载中 */
    private static final int DOWNLOAD = 1;
    /* 下载结束 */
    private static final int DOWNLOAD_FINISH = 2;
    /* 保存解析的XML信息 */
    HashMap<String, String> mHashMap;
    /* 下载保存路径 */
    private String mSavePath;
    /* 记录进度条数量 */
    private int progress;
    /* 是否取消更新 */
    private boolean cancelUpdate = false;

    private Context mContext;
    /* 更新进度条 */
    private ProgressBar mProgress;
    private Dialog mDownloadDialog;
    private String androidUrl;

    public boolean back;

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                // 正在下载
                case DOWNLOAD:
                    // 设置进度条位置
                    mProgress.setProgress(progress);
                    break;
                case DOWNLOAD_FINISH:
                    // 安装文件
                    installApk();


                    break;
                default:
                    break;
            }
        }

        ;
    };

    public UpdateManager(Context context, String androidUrl) {
        this.mContext = context;
        this.androidUrl = androidUrl;
    }

    /**
     * 检测软件更新
     */
    public void checkUpdate() {
        // 显示提示对话框
        showNoticeDialog();
    }

    /**
     * 显示软件更新对话框
     */
    private void showNoticeDialog() {
        // 构造对话框
        Builder builder = new Builder(mContext);
        builder.setTitle("软件更新");
        builder.setMessage("检测到新版本，立即更新吗");
        // 更新
        builder.setPositiveButton("更新",
                new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        // 显示下载对话框
                        showDownloadDialog();
                    }
                });
        // 稍后更新
        builder.setNegativeButton("稍后更新",
                new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        back = true;

                        dialog.dismiss();
                    }
                });
        Dialog noticeDialog = builder.create();
        noticeDialog.show();
    }

    MyLoadingDialog.Builder builder4;
    LoadingDialog dialog4;

    /**
     * 显示软件下载对话框
     */
    private Dialog dialog;

  /*  public void showDownloadDialog() {

        // 构造软件下载对话框
        Builder builder = new Builder(mContext, R.style.MyDialogStyle);
        builder.setCancelable(false);
//        builder.setTitle("正在更新");
        // 给下载对话框增加进度条
        dialog=new Dialog(mContext);

        Window window = dialog.getWindow();

        window.setGravity(Gravity.BOTTOM);
        final LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.item_splash_upversion_download_progress, null);
        mProgress = (ProgressBar) v.findViewById(R.id.update_progress);

//设置dialog的宽高为屏幕的宽高mContainerView = getLayoutInflater().inflate(R.layout.widget_yuedudialog, null);
//        mContainerView.setMinimumWidth(10000);
//        mDialog.setContentView(mContainerView);

        v.setMinimumWidth(10000);

        builder.setView(v);


        mDownloadDialog = builder.create();
        mDownloadDialog.show();

        // 现在文件
        downloadApk();
    }*/

    Dialog bottomDialog;

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public void showDownloadDialog() {
        // 构造软件下载对话框
        Builder builder = new Builder(mContext);
        builder.setCancelable(false);
        bottomDialog = new Dialog(mContext);
        View contentView = LayoutInflater.from(mContext).inflate(R.layout.item_splash_upversion_download_progress, null);
        mProgress = (ProgressBar) contentView.findViewById(R.id.update_progress);


        bottomDialog.setContentView(contentView);
        ViewGroup.LayoutParams layoutParams = contentView.getLayoutParams();
        layoutParams.width = mContext.getResources().getDisplayMetrics().widthPixels;
        contentView.setLayoutParams(layoutParams);
        WindowManager.LayoutParams lp = bottomDialog.getWindow().getAttributes();

//        lp.alpha=0.f;//（0.0-1.0）

        bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
//        bottomDialog.getWindow().setBackgroundDrawable(mContext.getDrawable(R.color.transorf));
//        bottomDialog.getWindow().

        bottomDialog.setCanceledOnTouchOutside(false);
        bottomDialog.setCancelable(false);


// windowFrame android:backgroundDimEnabled
// bottomDialog.getWindow().requestWindowFeature(Window.FEATURE_NO_TITLE);
//        bottomDialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
//        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
//        bottomDialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        bottomDialog.getWindow().setBackgroundDrawable(mContext.getDrawable(R.color.tranport));
//bottomDialog.getWindow().setbackg
        bottomDialog.getWindow().setDimAmount(0f);

        lp.x = 300; // 新位置X坐标
        lp.y = 300; // 新位置Y坐标
//        lp.width = 300; // 宽度
//        lp.height = 300; // 高度
        lp.alpha = 0.7f; // 透明度

// dialog.onWindowAttributesChanged(lp);
//(当Window的Attributes改变时系统会调用此函数)
        bottomDialog.getWindow().setAttributes(lp);


        bottomDialog.show();

        // 现在文件
        downloadApk();
    }

    /**
     * 下载apk文件
     */
    private void downloadApk() {
        // 启动新线程下载软件
        new downloadApkThread().start();
    }

    /**
     * 下载文件线程
     *
     * @author coolszy
     * @date 2012-4-26
     * @blog http://blog.92coding.com
     */
    private class downloadApkThread extends Thread {
        @Override
        public void run() {
            try {
                // 判断SD卡是否存在，并且是否具有读写权限
                if (Environment.getExternalStorageState().equals(
                        Environment.MEDIA_MOUNTED)) {
                    // 获得存储卡的路径
                    String sdpath = Environment.getExternalStorageDirectory()
                            + "/";
                    mSavePath = sdpath + "xmrxbbt";
                    URL url = new URL(androidUrl);
                    // 创建连接
                    HttpURLConnection conn = (HttpURLConnection) url
                            .openConnection();
                    conn.connect();
                    // 获取文件大小
                    int length = conn.getContentLength();
                    // 创建输入流
                    InputStream is = conn.getInputStream();

                    File file = new File(mSavePath);
                    // 判断文件目录是否存在
                    if (!file.exists()) {
                        file.mkdir();
                    }
                    File apkFile = new File(mSavePath, "demo");
                    FileOutputStream fos = new FileOutputStream(apkFile);
                    int count = 0;
                    // 缓存
                    byte buf[] = new byte[1024];
                    // 写入到文件中
                    do {
                        int numread = is.read(buf);
                        count += numread;
                        // 计算进度条位置
                        progress = (int) (((float) count / length) * 100);
                        // 更新进度
                        mHandler.sendEmptyMessage(DOWNLOAD);
                        if (numread <= 0) {
                            // 下载完成
                            mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
                            break;
                        }
                        // 写入文件
                        fos.write(buf, 0, numread);


                    } while (!cancelUpdate);// 点击取消就停止下载.
                    fos.close();
                    is.close();
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 取消下载对话框显示
//            mDownloadDialog.dismiss();
            bottomDialog.dismiss();

        }
    }

    ;

    /**
     * 安装APK文件
     */
    private void installApk() {


        File apkfile = new File(mSavePath, "demo");
//		if (!apkfile.exists()) {
//			return;
//		}
//		// 通过Intent安装APK文件
//		Intent i = new Intent(Intent.ACTION_VIEW);//
//		i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//		i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
//				"application/vnd.android.package-archive");
//		mContext.startActivity(i);
        if (mContext == null || TextUtils.isEmpty(apkfile.toString())) {
            return;
        }


        File file = new File(apkfile.toString());
        Intent intent = new Intent(Intent.ACTION_VIEW);

        //判读版本是否在7.0以上
        if (Build.VERSION.SDK_INT >= 24) {
            //provider authorities
            Uri apkUri = FileProvider.getUriForFile(mContext, "com.majiabao.udzt.file_provider", file);
            //Granting Temporary Permissions to a mContext
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        }

        mContext.startActivity(intent);
//		android.os.Process.killProcess(android.os.Process.myPid());//com.bxvip.app.bxvip369cai01
     /*   if (isAppInstalled("com.bxvip.app.bxvip369cai01")) {
            unstallApp();
        }*/
        Intent mIntent = new Intent(ACTION_NAME);
        mIntent.putExtra("yaner", "发送广播，相当于在这里传送数据");
        //发送广播
        mContext.sendBroadcast(mIntent);

    }

    private final String ACTION_NAME = "跳转到哪里呢";

    public boolean isBack() {
        return back;
    }

    public void setBack(boolean back) {
        this.back = back;
    }


}
